import Mock from 'mockjs';
import type { MockjsRequestOptions } from 'mockjs';

// 存储用户数据
let userData = {
  id: 1001,
  userType: 'admin',
  mobile: '13800138000',
  userName: '张三',
  nickname: '小张',
  avatar: 'https://img1.baidu.com/it/u=1618864032,2189629152&fm=253&fmt=auto&app=138&f=JPEG?w=200&h=200',
  status: '启用'
};

// 个管-登录帐号-查看
Mock.mock('/api/user/getLoginUserInfo', 'post', () => ({
  code: '100',
  message: '操作成功',
  data: {
    user: {
      ...userData,
      createdAt: '2025-06-16 20:40:26',
      updatedAt: null,
      deletedAt: null
    },
    roleList: [
      {
        id: 1,
        roleName: '超级管理员',
        type: '系统角色'
      }
    ],
    permissionList: [
      { permissionCode: '1201', permissionName: '查看个人账号信息' },
      { permissionCode: '1202', permissionName: '编辑个人账号信息' },
      { permissionCode: '1203', permissionName: '查看账号权限' },
      { permissionCode: '0701', permissionName: '企业查看' }
    ]
  }
}));

// 个管-登录帐号-编辑
Mock.mock('/api/user/editLoginUserInfo', 'post', (options: MockjsRequestOptions & { body: unknown }) => {
  try {
    let params: Record<string, unknown> = {};

    // 如果是 FormData 格式
    if (options.body instanceof FormData) {
      for (const [key, value] of options.body.entries()) {
        params[key] = value;
      }
    }
    // 如果是 JSON 字符串格式
    else if (typeof options.body === 'string') {
      try {
        params = JSON.parse(options.body);
      } catch {
        // 如果不是有效的 JSON，尝试解析 URL 编码的表单数据
        const searchParams = new URLSearchParams(options.body);
        for (const [key, value] of searchParams.entries()) {
          params[key] = value;
        }
      }
    }

    console.log('编辑个人信息参数:', params);

    // 验证必要参数
    if (!params.userName) {
      return {
        code: '400',
        message: '用户名不能为空',
        data: null
      };
    }

    // 更新用户数据
    userData = {
      ...userData,
      userName: params.userName as string,
      avatar: (params.avatar as string) || userData.avatar
    };

    // 如果是修改手机号
    if (params.newMobile && params.newMobileCode) {
      userData.mobile = params.newMobile as string;
    }

    console.log('更新后的用户数据:', userData);

    return {
      code: '100',
      message: '编辑成功',
      data: null
    };
  } catch (error) {
    console.error('处理编辑请求失败:', error);
    return {
      code: '500',
      message: '处理请求失败',
      data: null
    };
  }
});
